//
//  GoogleSpreadsheet.m
//  itaka
//
//  Created by Robert Soszynski on 1/14/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "GoogleSpreadsheet.h"

@implementation GoogleSpreadsheet
@synthesize delegate;
@synthesize spreadsheet, worksheet, record;
@synthesize spreadsheetIdentifier, worksheetIdentifier, recordIdentifier;

- (id)init {
    if (self = [super init])
    {
        service = [[GDataServiceGoogleSpreadsheet alloc] init];
        
        [service setShouldCacheResponseData:YES];
        [service setServiceShouldFollowNextLinks:YES];
        
        // iPhone apps will typically disable caching dated data or will call
        // clearLastModifiedDates after done fetching to avoid wasting
        // memory.
    }
    return self;
}

- (void) setCredentials:(NSString *) username: (NSString*) password {
    [service setUserCredentialsWithUsername:username password:password];
}

- (void) startProceeding:(NSString*) spreadsheetId: (NSString*) worksheetId: (NSString*) recordId {
    [self setSpreadsheetIdentifier:spreadsheetId];
    [self setWorksheetIdentifier:worksheetId];
    [self setRecordIdentifier:recordId];
    
    [self pickSpreadsheet:[self spreadsheetIdentifier]];
}

// begin retrieving the list of spreadsheets
- (void) pickSpreadsheet:(NSString *) identifier {
    NSURL *feedURL = [NSURL URLWithString:kGDataGoogleSpreadsheetsPrivateFullFeed];
    
    [service fetchFeedWithURL:feedURL
                     delegate:self
            didFinishSelector:@selector(spreadsheetsTicket:finishedWithFeed:error:)];
}

- (void) spreadsheetsTicket:(GDataServiceTicket *)ticket
           finishedWithFeed:(GDataFeedSpreadsheet *)feed
                      error:(NSError *)error {

    if (error == nil) { 
        for (GDataEntrySpreadsheet *ss in [feed entries]) {
            NSString *title = [[ss title] stringValue];
            if ([title isEqualToString:spreadsheetIdentifier]) {
                [self setSpreadsheet:ss];
                //NSLog(@"spreadsheet: %@", [[self spreadsheet] description]);
                [self pickWorksheet:[self worksheetIdentifier]];
                return;
            }
        }
    } else 
        [self delegateError :error];
}

// begin retrieving the list of worksheets
- (void) pickWorksheet:(NSString *) identifier {
    [service fetchFeedWithURL:[spreadsheet worksheetsFeedURL]
                     delegate:self
            didFinishSelector:@selector(worksheetsTicket:finishedWithFeed:error:)];
}

- (void) worksheetsTicket:(GDataServiceTicket *)ticket
         finishedWithFeed:(GDataFeedWorksheet *)feed
                    error:(NSError *)error {
    
    if (error == nil) {  
        for (GDataEntryWorksheet *ws in [feed entries]) {
            NSString *title = [[ws title] stringValue];
            if ([title isEqualToString:worksheetIdentifier]) {
                [self setWorksheet:ws];
                //NSLog(@"Worksheet: %@", [[self worksheet] description]);
                [self pickRecord:[self recordIdentifier]];
                return;
            }
        }
    } else 
        [self delegateError :error];
}

// begin retrieving the list of records
- (void) pickRecord:(NSString *) identifier {
    [service fetchFeedWithURL:[worksheet listFeedURL]
                     delegate:self
            didFinishSelector:@selector(listsTicket:finishedWithFeed:error:)];
}

- (void) listsTicket:(GDataServiceTicket *)ticket
    finishedWithFeed:(GDataFeedWorksheet *)feed
               error:(NSError *)error {
    if (error == nil) {  
        for (GDataEntrySpreadsheetList *entry in [feed entries]) {
            if ([[[entry title] stringValue] isEqualToString:recordIdentifier] ) {
                [self setRecord:entry];
                //NSLog(@"Record: %@", [[self record] description]);
                [[self delegate] spreadsheetInitCompleted];
                return;
            }
        }
        [self addRecord];
    } else
        [self delegateError :error];
}

- (void) updateRecord {
    [service fetchEntryByUpdatingEntry:record
                              delegate:self
                     didFinishSelector:@selector(updateRecordTicket:finishedWithFeed:error:)];
}

- (void) updateRecordTicket:(GDataServiceTicket *)ticket
    finishedWithFeed:(GDataEntrySpreadsheetList *)feed
               error:(NSError *)error {
    
    if (error == nil) { 
        [self setRecord:feed];
        NSLog(@"Spreadsheet updated");
    } else 
        [self delegateError: (NSError*) error];
}

- (void) setCellValue:(NSString*) key: (NSString*) value {
    GDataSpreadsheetCustomElement *element = [GDataSpreadsheetCustomElement elementWithName:key stringValue:value];
    [record setCustomElement:element];
}

- (void) addRecord {
    record = [[GDataEntrySpreadsheetList alloc]init];
    [record setTitleWithString: recordIdentifier];
    [self setCellValue:@"identifier": recordIdentifier];
    
    [service fetchEntryByInsertingEntry:record 
                             forFeedURL:[worksheet listFeedURL] 
                               delegate:self 
                      didFinishSelector:@selector(addRecordTicket:addedEntry:error:)];
}

- (void) addRecordTicket:(GDataServiceTicket *)ticket
           addedEntry:(GDataEntrySpreadsheetList *)entry
                      error:(NSError *)error {
    if (error == nil) 
        [self pickRecord: recordIdentifier];
    else 
        [self delegateError :error];
}

- (void) delegateError: (NSError*) err {
    NSLog(@"Error: %@", err);
    NSString *error;
    if ((error = [[err userInfo] objectForKey:@"NSLocalizedDescription"])) {}
    else if ((error = [[err userInfo] objectForKey:@"error"])) {}
    
    [[self delegate] spreadsheetError: error];
}

@end






